package com.example.function.integration.utils;

import com.jcraft.jsch.*;

/**
 * @description:SFTP工具类
 * @className:SftpUtils
 * @author:ext.fengcheng
 * @date:2023/9/27 15:33
 */
public class SftpUtils {

    ThreadLocal<ChannelSftp> channelThreadLocal = new ThreadLocal<>();
    ThreadLocal<Session> sessionThreadLocal = new ThreadLocal<>();

    public String username;
    public String password;
    public String remoteHost;
    public Integer remotePort;
    public String charset;

    public SftpUtils(String remoteHost, Integer remotePort, String username, String password, String charset) throws JSchException, SftpException {
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
        this.username = username;
        this.password = password;
        this.charset = charset;
        connect();
    }

    public void uploadFile(ChannelSftp channel, String src, String dest) throws SftpException {
        channel.put(src, dest);
    }

    public void uploadFile(String src, String dest) throws SftpException, JSchException {
        uploadFile(getChannel(), src, dest);
    }

    public void connect() throws JSchException, SftpException {
        JSch jSch = new JSch();
        Session session = jSch.getSession(username, remoteHost, remotePort);
        session.setPassword(password);
        session.setConfig("PreferredAuthentications", "password");
        session.setConfig("StrictHostKeyChecking", "no");// 为session重新设置参数
        session.connect();
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect(5000);
        channel.setFilenameEncoding(charset);
        channelThreadLocal.set(channel);
        sessionThreadLocal.set(session);
    }

    public void disconnectAll() throws JSchException, SftpException {
        ChannelSftp channel = getChannel();
        if (channel != null && channel.isConnected()) {
            channel.disconnect();
        }
        Session session = getSession();
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }

    public ChannelSftp getChannel() throws JSchException, SftpException {
        ChannelSftp channelSftp = channelThreadLocal.get();
        if (channelSftp == null) {
            connect();
        }
        return channelThreadLocal.get();
    }

    public Session getSession() throws JSchException, SftpException {
        Session session = sessionThreadLocal.get();
        if (session == null) {
            connect();
        }
        return sessionThreadLocal.get();
    }
}
